package com.paradisecloudtech.vc.system.mvp.presenter;

import com.common.library.base.BasePresenter;
import com.common.library.base.BaseView;
import com.paradisecloudtech.vc.system.mvp.bean.LoginResultBean;
import com.paradisecloudtech.vc.system.mvp.view.LoginView;
import com.paradisecloudtech.vc.system.mvp.model.LoginModel;

import io.reactivex.Observer;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;

public class LoginPresenter implements BasePresenter {

    private LoginModel loginModel;
    private LoginView loginView;
    private CompositeDisposable compositeDisposable;

    public LoginPresenter() {
        this.loginModel = new LoginModel();
        compositeDisposable = new CompositeDisposable();
    }

    @Override
    public void start() {

    }

    @Override
    public void attachView(BaseView loginView) {
        this.loginView = (LoginView) loginView;
    }

    @Override
    public void detachView() {
        this.loginView = null;
    }

    @Override
    public boolean isViewDetach() {
        return !(this.loginView == null);
    }

    public void requestLoginData(String name, String password) {
        if (isViewDetach()) {
            loginView.startLogin();
        }
        loginModel.requestLoginData(name, password)
                .subscribe(new Observer<LoginResultBean>() {

                    @Override
                    public void onSubscribe(Disposable d) {
                        compositeDisposable.add(d);
                    }

                    @Override
                    public void onNext(LoginResultBean s) {
                        if (isViewDetach()) {
                            loginView.loginSuccess(s);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        if (isViewDetach()) {
                            loginView.endLogin();
                        }
                    }

                    @Override
                    public void onComplete() {
                        if (isViewDetach()) {
                            loginView.endLogin();
                        }
                    }
                });


    }


    @Override
    public void stop() {
        if (!compositeDisposable.isDisposed()) {
            compositeDisposable.dispose();
        }
    }
}
